<?php

ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
ini_set('memory_limit', '1024M');

/**
 * 淘宝联盟订单 每天凌晨4:00更新一次 biz-admin 机器
 */
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\tools\TbkUnion;
use Doraemon\tools\Curl;
use Doraemon\tools\Log;
use Biz\model\wiki\TaoBaoOrders;

$startTime = $argv[1] ?? date('Y-m-d 00:00:00', strtotime('-1 day'));
$endTime = $argv[2] ?? date('Y-m-d H:i:s', strtotime($startTime) + 86399);

run($startTime, $endTime, 1);//按照订单淘客创建时间查询
run($startTime, $endTime, 4);//按照订单更新时间

function run($startTime, $endTime, $type)
{
    $start = strtotime($startTime);
    do {
        $end = $start + 600;
        $end = ($end <= strtotime($endTime)) ? $end : strtotime($endTime);
        getOrder($start, $end, $type);
        $start = $start + 600;
    } while ($start <= $end);
}

function getOrder($start, $end, $type = 1, $positionIndex = '')
{
    $startTime = date('Y-m-d H:i:s', $start);
    $endTime = date('Y-m-d H:i:s', $end);
    var_dump('查询订单#type:' . $type . '#start:' . $startTime . '#end:' . $endTime . '#position_index:' . $positionIndex);
    $res = TbkUnion::tbkOrderDetails(1, $startTime, $endTime, 80, 1, $positionIndex);
    if ($res) {
        $positionIndex = $res['position_index'];
        $hasNext = $res['has_next'];
        if (isset($res['results']['publisher_order_dto']) && $res['results']['publisher_order_dto']) {
            foreach ($res['results']['publisher_order_dto'] as $row) {
                InsertData($row);

            }
        } else {
            var_dump($res, '######没查询订单');
        }
        if ($hasNext) {
            getOrder($start, $end, $type, $positionIndex);
        }
    }
}

function InsertData($data){
   $OrderInfo =  TaoBaoOrders::getByWhere(['trade_id' => $data['trade_id'] ,'trade_parent_id' => $data['trade_parent_id']]);
   if($OrderInfo && is_array($OrderInfo)){
       TaoBaoOrders::updateData($data , ['id' =>$OrderInfo['id']]);
   }else{
       TaoBaoOrders::insertData($data);
   }
}

function sendData($row)
{
    return true;
    $url = 'http://logcollector.hhzbi.com/v1/text/rebate_order_data';
    $params = [
        'body' => json_encode(['type' => 1, 'data' => $row]),
        'headers' => [
            'Accept' => 'text/plain;charset=utf-8',
            'Content-Type' => 'application/json; charset=utf-8',
        ]
    ];
    $result = Curl::Request('POST', $url, $params);
    if ($result['httpCode'] != 200 || $result['code'] != 1) {
        Log::debug('发送数据失败#' . $url, $result);
    }
}





